package com.yidu.ruifeng_logistics.redis;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author: 肖楚科
 * @date: 2021/3/9
 * @time: 13:52
 * @blog: com.yidu.ruifeng_logistics.redis
 * @description:
 */

public class RedisCache implements Cache {
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private String id;

    public RedisTemplate getRedisTemplate(){
        return ApplicationContextHolder.getBean("redisTemplate");
    }

    public RedisCache(String id){
        this.id = id;
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void putObject(Object key, Object value) {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.boundHashOps(getId()).put(key,value);
        logger.info("[结果放入到缓存中: "+getId()+"key:"+ key + "value" + value+" ]");
    }

    @Override
    public Object getObject(Object o) {
        RedisTemplate redisTemplate = getRedisTemplate();
        Object value = redisTemplate.boundHashOps(getId()).get(o);
        logger.info("即将取出的缓存key:"+o+"值:"+value);
        return value;
    }

    @Override
    public Object removeObject(Object o) {
        RedisTemplate redisTemplate = getRedisTemplate();
        logger.info("正在删除:"+o);
        return redisTemplate.boundHashOps(getId()).delete(o);
    }

    @Override
    public void clear() {
        RedisTemplate redisTemplate = getRedisTemplate();
        logger.info("正在清空缓存");
        redisTemplate.delete(getId());
    }

    @Override
    public int getSize() {
        RedisTemplate redisTemplate = getRedisTemplate();
        Long size = redisTemplate.boundHashOps(getId()).size();
        return size==null?0:size.intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }
}



